﻿CREATE PROCEDURE [dbo].[Book_GetList]
	@userId UNIQUEIDENTIFIER = NULL,
	@showHidden BIT = 0
AS
BEGIN

	DECLARE @books TABLE 
	(
		[BookId] UNIQUEIDENTIFIER
	)

	INSERT INTO @books ([BookId])
	SELECT DISTINCT b.[BookId]
	FROM [dbo].[text_Chapter] AS c
	INNER JOIN [dbo].[text_Book] AS b on c.[BookId] = b.[BookId]
	WHERE [ParentChapterId] IS NULL AND (@showHidden = 1 OR c.[IsPublished] = 1)

	SELECT b.[BookId]
				,	[ChapterId]
				,	[HashTag]
				,	[IsPublished]
				,	[Title]
				,	[Author]
				,	[CoverUrl]
	FROM [dbo].[text_Chapter] AS c
	INNER JOIN [dbo].[text_Book] AS b on c.[BookId] = b.[BookId]
	--WHERE [ParentChapterId] IS NULL AND (@showHidden = 1 OR c.[IsPublished] = 1)
	WHERE [ParentChapterId] IS NULL AND c.[BookId] IN (SELECT [BookId] FROM @books)

------------------- HEADERS ------------------------
	SELECT [ChapterId]
				,[ParentChapterId]
				,[BookId]
				,[HashTag]
				,[IsPublished]
				, /*CASE WHEN [Cost] IS NULL
					THEN NULL
					ELSE
						[dbo].[GetChapterCost]([ChapterId], @userId, [Cost])
					END*/ NULL AS [Cost]
				,[Order]
				,[Title]
				,[Hint]
				,[UpdateDate]
	FROM [dbo].[text_Chapter]
	WHERE (@showHidden = 1 OR [IsPublished] = 1) AND [BookId] IN (SELECT [BookId] FROM @books)
------------------- HEADERS ------------------------

------------------- INTRO ------------------------
	SELECT [TextId]
				,[ChapterId]
				,[Value]
				,[Order]
				,[Tag]
	FROM [dbo].[text_Text]
	WHERE [ChapterId] IN (
		SELECT [ChapterId]
		FROM [dbo].[text_Chapter]
		WHERE [ParentChapterId] IS NULL AND [BookId] IN (SELECT [BookId] FROM @books)
	)
------------------- INTRO ------------------------

END